//
//  SendTopicViewController.m
//  1gene
//
//  Created by 1jiyin on 16/3/15.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//******************发帖******************
#import "SendTopicViewController.h"
static int seconds;
@interface SendTopicViewController ()<ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>

/*
 *帖子标题
 */
@property(nonatomic,copy)UITextField *topicTextField;

/*
 *输入的内容
 */
@property(nonatomic,strong)UITextView *contentText;


/*
 *标签的id
 */
@property(nonatomic,copy)NSString *tagId;



/*
 *选择按钮
 */
@property(nonatomic,copy)UIButton *uploadPhotoBtn;
/*
 *从相册选取的图片的数量
 */
@property(nonatomic,assign)NSInteger imageNumber;

/*
 *相册
 */
@property(nonatomic,copy)ZYQAssetPickerController *picker;
/*
 *定时器
 */
@property(nonatomic,copy)NSTimer *myTimer;
/*
 *从相册选择的图片添加到一个数组里
 */
//@property(nonatomic,copy)NSMutableArray *imageViewArray;
/*
 *从相册选择的图片添加到一个数组里
 */
@property(nonatomic,copy)NSMutableArray *imageArray;
/*
 *自定义一个View来贴圈子选择
 */
/*
 *圈子
 */
@property(nonatomic,copy)UILabel *quanzi;
/*
 *自定义view
 */
@property(nonatomic,copy)UIView *customView;
@end

@implementation SendTopicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:[UIView new]];
    //_imageViewArray=[NSMutableArray array];
    _imageArray=[NSMutableArray array];
    [self createNavigation];
    
    [self createUI];
    // Do any additional setup after loading the view.
}
-(void)createUI
{
    //标题
    UITextField *topicTextField=[[UITextField alloc]initWithFrame:CGRectMake(5, 20+44+5, self.view.frame.size.width-5-5, 50)];
    topicTextField.placeholder=@" 标题";
    topicTextField.font=[UIFont systemFontOfSize:15];
    topicTextField.backgroundColor=[UIColor whiteColor];
    topicTextField.textColor=[UIColor grayColor];
    topicTextField.layer.borderColor=[UIColor colorWithRed:106/255.0 green:198/255.0 blue:223/255.0 alpha:1].CGColor;
    topicTextField.layer.borderWidth=1.0;
    topicTextField.layer.cornerRadius=2.0;
    [self.view addSubview:topicTextField];
    _topicTextField=topicTextField;
    
    
    UIView *hideKeyBoardView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    hideKeyBoardView.backgroundColor=[UIColor colorWithRed:174/255.0 green:181/255.0 blue:190/255.0 alpha:1];
    UIButton *hideKeyBoardBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    hideKeyBoardBtn.frame=CGRectMake(hideKeyBoardView.frame.size.width-30, 0, 30, 30);
    [hideKeyBoardBtn setBackgroundImage:[UIImage imageNamed:@"baritem_bottom_hl.png"] forState:UIControlStateNormal];
    [hideKeyBoardBtn addTarget:self action:@selector(hideKeyBoardBtn:) forControlEvents:UIControlEventTouchUpInside];
    [hideKeyBoardView addSubview:hideKeyBoardBtn];
    topicTextField.inputAccessoryView=hideKeyBoardView;
    
    
    //内容
    UITextView *contentText=[[UITextView alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(topicTextField.frame)+5, self.view.frame.size.width-5-5, 150)];
    contentText.backgroundColor=[UIColor whiteColor];
    contentText.text=@"输入内容";
    contentText.delegate=self;
    contentText.layer.borderColor=[UIColor colorWithRed:106/255.0 green:198/255.0 blue:223/255.0 alpha:1].CGColor;
    contentText.layer.borderWidth=1.0;
    contentText.layer.cornerRadius=2.0;
    contentText.font=[UIFont systemFontOfSize:13];
    [self.view addSubview:contentText];
    contentText.inputAccessoryView=hideKeyBoardView;
    _contentText=contentText;
    
    
    //发表图片
    CGFloat img_w=(self.view.frame.size.width-5*6)/5.0;
    CGFloat img_h=img_w;
    UIButton *uploadPhotoBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    uploadPhotoBtn.frame=CGRectMake(5, CGRectGetMaxY(contentText.frame)+10, img_w, img_h);
    [uploadPhotoBtn setBackgroundImage:[UIImage imageNamed:@"btn_add_photo_s.png"] forState:UIControlStateNormal];
    [uploadPhotoBtn addTarget:self action:@selector(uploadPhotoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:uploadPhotoBtn];
    _uploadPhotoBtn=uploadPhotoBtn;
    
    
    //自定义一个View来贴圈子选择
    UIView *customView=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_uploadPhotoBtn.frame)+10, self.view.frame.size.width, 30)];
    [self.view addSubview:customView];
    _customView=customView;
    
    //选择圈子
    UILabel *huise=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 10, 30)];
    huise.backgroundColor=[UIColor grayColor];
    huise.font=[UIFont systemFontOfSize:12];
    huise.textColor=[UIColor blackColor];
    [customView addSubview:huise];


    UILabel *quanzi=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-10, 30)];
    quanzi.backgroundColor=[UIColor grayColor];
    quanzi.text=@"选择标签";
    _quanzi=quanzi;
    quanzi.font=[UIFont systemFontOfSize:15];
    quanzi.textColor=[UIColor blackColor];
    [customView addSubview:quanzi];
    
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(self.view.frame.size.width-30, 0, 30, 30);
    [btn setBackgroundImage:[UIImage imageNamed:@"baritem_left_hl.png"] forState:UIControlStateNormal];
    [customView addSubview:btn];
    
    //盖按钮
    UIButton *selectedBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    selectedBtn.frame=CGRectMake(0, 0, self.view.frame.size.width, 30);
    [selectedBtn addTarget:self action:@selector(selectedBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:selectedBtn];
    //_selectedBtn=selectedBtn;
}

#pragma mark 选择圈子
-(void)selectedBtnClick:(UIButton *)sender
{
    NSLog(@"选择圈子");
    CircleViewController *vc=[[CircleViewController alloc]init];
    vc.biaoqianState=0;
    vc.returnCircle=^(NSString *circle,NSString *tagId){
        _quanzi.text=circle;
        _tagId=tagId;
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark 从相册选取图片
-(void)uploadPhotoBtnClick:(UIButton *)sender
{
    UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
    [sheet showInView:self.view];
    
    
    [_contentText resignFirstResponder];
//    if (_imageNumber==10) {
//        if (_myTimer==nil) {
//            _myTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil  repeats:YES];
//        }else{
//            
//        }
//        
//        [self.view showPromptMessage:YES and:@"最多只能上传10张图片"];
//    }else{
//        ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
//        picker.maximumNumberOfSelection = 10-_imageNumber;
//        picker.assetsFilter = [ALAssetsFilter allPhotos];
//        picker.showEmptyGroups=YES;
//        picker.delegate=self;
//        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
//            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
//                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
//                return duration >= 8;
//            } else {
//                return YES;
//            }
//        }];
//        _picker=picker;
//        [self presentViewController:picker animated:YES completion:NULL];
//    }
   
}
//隐藏键盘
-(void)hideKeyBoardBtn:(UIButton *)sender
{
    [self.navigationController.view endEditing:YES];
}




-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"==============%ld",buttonIndex);
    if(buttonIndex==0){
            if (_imageNumber==10) {
                if (_myTimer==nil) {
                    _myTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil  repeats:YES];
                }else{
        
                }
        
                [self.view showPromptMessage:YES and:@"最多只能上传10张图片"];
            }else{
                UIImagePickerController *picker=[[UIImagePickerController alloc]init];
                picker.delegate=self;
                picker.sourceType=UIImagePickerControllerSourceTypeCamera;
                picker.allowsEditing=YES;
                [self presentViewController:picker animated:YES completion:nil];
            }
        
    }else if (buttonIndex==1){
            if (_imageNumber==10) {
                if (_myTimer==nil) {
                    _myTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil  repeats:YES];
                }else{
        
                }
        
                [self.view showPromptMessage:YES and:@"最多只能上传10张图片"];
            }else{
                ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
                picker.maximumNumberOfSelection = 10-_imageNumber;
                picker.assetsFilter = [ALAssetsFilter allPhotos];
                picker.showEmptyGroups=YES;
                picker.delegate=self;
                picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
                    if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                        NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                        return duration >= 8;
                    } else {
                        return YES;
                    }
                }];
                _picker=picker;
                [self presentViewController:picker animated:YES completion:NULL];
            }
    }else{
        
    }
        
}


#pragma mark 启动定时器
-(void)timerRun
{
    if (seconds==1) {
        [self.view showPromptMessage:NO and:nil];
        [_myTimer invalidate];
        _myTimer=nil;
        seconds=0;
    }else{
        seconds++;
    }
}

#pragma mark 自定义navigation
-(void)createNavigation
{
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    title.text=@"发帖";
    title.font=[UIFont systemFontOfSize:22];
    title.textAlignment=NSTextAlignmentCenter;
    title.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=title;
    //取消按钮
    UIButton *cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame=CGRectMake(0, 0, 30, 30);
    cancelBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:cancelBtn];
    
    
    //发布按钮
    UIButton *sendBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame=CGRectMake(0, 0, 30, 30);
    sendBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [sendBtn setTitle:@"发布" forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:sendBtn];
}
#pragma mark 取消
-(void)cancelBtnClick:(UIButton *)sender
{
    if (_navigationBarState==1) {
        self.navigationController.navigationBar.hidden=YES;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 发布
-(void)sendBtnClick:(UIButton *)sender
{
    if (_topicTextField.text.length>0&&_contentText.text.length>=20&&![_contentText.text isEqualToString:@"输入内容"]&&_tagId) {
        [self upLoadImage];
    }
    if (_topicTextField.text.length==0) {
        [self.view showTiShiMessage:@"标题不能为空"];
        return;
    }
    if (_contentText.text.length<20&&_topicTextField.text.length>0) {
        [self.view showTiShiMessage:@"内容必须为20字以上"];
        return;
    }
    if (_contentText.text.length>=20&&_topicTextField.text.length>0&&_tagId==nil) {
        [self.view showTiShiMessage:@"请选择一个标签"];
        return;
    }
    
}

//上传图片
-(void)upLoadImage
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    [self.view isLoading:YES];
    [manager POST:[NSString stringWithFormat:SendTopic,token] parameters:@{@"title":_topicTextField.text,@"content":_contentText.text,@"tag_id":_tagId} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i=0 ;i<_imageArray.count;i++) {
            //第一步是将图片转换成二进制数据流
            //NSData * photoData = UIImagePNGRepresentation((id)_dataArray[i]);
            //由于上传的图片是JPG格式的，所以用下面的方法
            NSData * photoData = UIImageJPEGRepresentation(_imageArray[i], 0.5);
            // 获得一个永不重复的随机的字符串
            NSString * imageName =[[NSUUID UUID] UUIDString];
            
            [formData appendPartWithFileData:photoData name:@"media_list[]" fileName:imageName mimeType:@"image/jpeg"];
        }
        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view isLoading:NO];
        [self.view showTiShiMessage:@"发帖成功"];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"反馈的信息=====%@",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        [self.view showTiShiMessage:@"发帖失败"];
        NSLog(@"error===%@",error.localizedDescription);
    }];
}
















//textView的代理
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"输入内容"]) {
        textView.text=@"";
    }
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length<1) {
        textView.text=@"输入内容";
    }
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        for (int i=0; i<assets.count; i++) {
//            ALAsset *asset=assets[i];
//             UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
//            [_imageArray addObject:tempImg];
//        }
//        [self makePhotoLocationWithTag:100];
//    });
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i=0; i<assets.count; i++) {
            ALAsset *asset=assets[i];
            UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            [_imageArray addObject:tempImg];
        }
        [self makePhotoLocationWithTag:100];
    });
    
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *tempImg=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
            [_imageArray addObject:tempImg];
            [self makePhotoLocationWithTag:100];
            [self dismissViewControllerAnimated:YES completion:nil];
    });
}
#pragma mark 响应手势
-(void)tapHappen:(UITapGestureRecognizer *)tap
{
    
    UIImageView *imgView1=(id)tap.view;
   // NSLog(@"每张图片的下标========%ld",imgView1.tag);
    PhotoBigImageViewController *vc=[[PhotoBigImageViewController alloc]init];
    vc.imageTag=imgView1.tag;
    vc.img=imgView1.image;
    vc.deleteImage=^(NSInteger imgTag){
        [self makePhotoLocationWithTag:imgTag];
            };
    [self.navigationController pushViewController:vc animated:YES];
}

//图片的位置移动
-(void)makePhotoLocationWithTag:(NSInteger)imgTag
{
    for (int i=0; i<_imageArray.count; i++) {
        UIImageView *imgView=(id)[self.view viewWithTag:10+i];
        [imgView removeFromSuperview];
    }
    //[_imageViewArray removeObjectAtIndex:imgTag];
    // NSLog(@"=============%ld",imgTag);
    if (imgTag==100) {
        
    }else{
        [_imageArray removeObjectAtIndex:imgTag-10];
    }
    
    // NSLog(@"=============%ld",_imageArray.count);
    
    for (int i=0; i<2; i++) {
        for (int j=0; j<5; j++) {
            if (i*5+j<_imageArray.count) {
                UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(5+(_uploadPhotoBtn.frame.size.width+5)*j, CGRectGetMaxY(_contentText.frame)+10+(_uploadPhotoBtn.frame.size.height+5)*i, _uploadPhotoBtn.frame.size.width, _uploadPhotoBtn.frame.size.height)];
                imgView.tag=10+i*5+j;
                //每一个ImageView添加一个手势
                UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHappen:)];
                [imgView addGestureRecognizer:tap];
                imgView.userInteractionEnabled=YES;
                imgView.clipsToBounds=YES;
                imgView.userInteractionEnabled=YES;
                dispatch_async(dispatch_get_main_queue(), ^{
                    imgView.image=_imageArray[i*5+j];
                    [self.view addSubview:imgView];
                });
                //[self.view addSubview:imgView];
            }
        }
    }
    _imageNumber=_imageArray.count;
    if (_imageArray.count<5) {
        dispatch_async(dispatch_get_main_queue(), ^{
            _uploadPhotoBtn.frame=CGRectMake(5+(_uploadPhotoBtn.frame.size.width+5)*_imageArray.count, CGRectGetMaxY(_contentText.frame)+10, _uploadPhotoBtn.frame.size.width, _uploadPhotoBtn.frame.size.height);
            _customView.frame=CGRectMake(0, CGRectGetMaxY(_uploadPhotoBtn.frame)+10, self.view.frame.size.width, 30);
        });
        
    }else if (_imageArray.count>4&&_imageArray.count<10){
        dispatch_async(dispatch_get_main_queue(), ^{
            _uploadPhotoBtn.frame=CGRectMake(5+(_uploadPhotoBtn.frame.size.width+5)*(_imageArray.count-5), CGRectGetMaxY(_contentText.frame)+10+(_uploadPhotoBtn.frame.size.height+5)*1, _uploadPhotoBtn.frame.size.width, _uploadPhotoBtn.frame.size.height);
            _customView.frame=CGRectMake(0, CGRectGetMaxY(_uploadPhotoBtn.frame)+10, self.view.frame.size.width, 30);
        });
        
        
    }else if (_imageArray.count==10){
        dispatch_async(dispatch_get_main_queue(), ^{
            _uploadPhotoBtn.frame=CGRectMake(5, CGRectGetMaxY(_contentText.frame)+10+(_uploadPhotoBtn.frame.size.height+5)*2, _uploadPhotoBtn.frame.size.width, _uploadPhotoBtn.frame.size.height);
            _customView.frame=CGRectMake(0, CGRectGetMaxY(_uploadPhotoBtn.frame)+10, self.view.frame.size.width, 30);
        });
        
    }

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.navigationController.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
